import React, { useEffect, useRef, useCallback } from 'react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';

interface XTermProps {
  connectionId: string;
  onData: (data: string) => void;
  onReady?: (terminal: Terminal) => void;
  theme?: 'light' | 'dark';
}

const XTerm: React.FC<XTermProps> = ({
  connectionId,
  onData,
  onReady,
  theme = 'light',
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const terminalRef = useRef<Terminal | null>(null);
  const fitAddonRef = useRef<FitAddon>(new FitAddon());

  // 初始化终端
  useEffect(() => {
    if (!containerRef.current) return;

    // 创建终端实例
    const terminal = new Terminal({
      theme: theme === 'dark' ? {
        background: '#1e1e1e',
        foreground: '#d4d4d4',
      } : {
        background: '#ffffff',
        foreground: '#000000',
      },
      fontSize: 14,
      fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
      cursorBlink: true,
      scrollback: 10000,
      allowTransparency: true,
    });

    terminalRef.current = terminal;

    // 加载fit插件
    terminal.loadAddon(fitAddonRef.current);

    // 打开终端
    terminal.open(containerRef.current);

    // 初始适应
    setTimeout(() => {
      try {
        fitAddonRef.current.fit();
      } catch (e) {
        console.error('Fit failed:', e);
      }
    }, 100);

    // 监听数据输入
    const disposable = terminal.onData((data) => {
      onData(data);
    });

    // 调用onReady回调
    if (onReady) {
      onReady(terminal);
    }

    // 监听窗口大小变化
    const handleResize = () => {
      try {
        fitAddonRef.current.fit();
      } catch (e) {
        console.error('Fit on resize failed:', e);
      }
    };
    window.addEventListener('resize', handleResize);

    // 清理
    return () => {
      disposable.dispose();
      window.removeEventListener('resize', handleResize);
      terminal.dispose();
      terminalRef.current = null;
    };
  }, [connectionId, onData, onReady, theme]);

  // 自适应容器大小
  const fit = useCallback(() => {
    if (fitAddonRef.current) {
      try {
        fitAddonRef.current.fit();
      } catch (e) {
        console.error('Fit failed:', e);
      }
    }
  }, []);

  // 焦点处理
  const handleFocus = () => {
    if (terminalRef.current) {
      terminalRef.current.focus();
    }
  };

  return (
    <div
      ref={containerRef}
      className={`xterm-container xterm-theme-${theme}`}
      style={{
        width: '100%',
        height: '100%',
        minHeight: '400px',
      }}
      onClick={handleFocus}
    />
  );
};

export default XTerm;